package com.mapreduce;

import com.bean.People;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.net.URI;

public class ReadDBMapReduce extends Configured implements Tool {
    static class ReadDBMapper extends
            Mapper<LongWritable, People, LongWritable, People>{
        @Override
        protected void map(LongWritable key, People value, Mapper<LongWritable, People, LongWritable, People>.Context context) throws IOException, InterruptedException {
            // key:行索引      value:数据
            context.write(key, value);
        }
    }
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        // 构建输入输出路径
        DBConfiguration.configureDB(conf,
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://192.168.10.11:3306/briup",
                "root",
                "root");
        Path output = new Path(
                "hdfs://192.168.10.11:9000/dbread");
        FileSystem fs = FileSystem.get(
                new URI("hdfs://192.168.10.11:9000"),conf);
        if (fs.exists(output)) fs.delete(output,true);

        Job job = Job.getInstance(conf);
        job.setJobName("readdb");
        job.setJarByClass(this.getClass());

        job.setMapperClass(ReadDBMapper.class);
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(People.class);

        job.setNumReduceTasks(0);

        job.setInputFormatClass(DBInputFormat.class);
        DBInputFormat.setInput(job, People.class,
                "people","1=1",
                "id","id","name","age");

        TextOutputFormat.setOutputPath(job,output);
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(ToolRunner.run(new ReadDBMapReduce(),args));
    }
}
